package com.itic.mall.system.useraddress.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.mall.system.useraddress.persistence.dao.UserAddressDao;
import com.itic.mall.system.useraddress.persistence.model.UserAddress;
import com.itic.mall.system.useraddress.persistence.model.UserAddressExample;
import com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria;


@Service
@Transactional
public class UserAddressService
     extends CrudService<UserAddressDao,UserAddress,UserAddressExample> {
    @Autowired
    private UserAddressDao userAddressDao;

    /**
     * 用户添加新的收货地址并且为默认地址
     * @param address
     * @return
     */
	public String addMainAddress(UserAddress address) {
		//将其它 的收货 地址更新 为普通 地址
		UserAddress userAddress = new UserAddress();
		userAddress.setIsMain("0");
		UserAddressExample example = new UserAddressExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(address.getUserId());
		userAddressDao.updateByExampleSelective(userAddress, example);
		
		//添加当前的收货地址
		userAddressDao.insert(address);//添加新的收货 地址
		return SUCCESS;
	}

	/**
	 * 用户编辑收货地址并且设置为默认地址
	 * @param address
	 * @return
	 */
	public String editMainAddress(UserAddress address) {
		//将其它 的收货 地址更新 为普通 地址
		UserAddress userAddress = new UserAddress();
		userAddress.setIsMain("0");
		
		UserAddressExample example = new UserAddressExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(address.getUserId());
		userAddressDao.updateByExampleSelective(userAddress, example);
		
		//更新当前的收货地址
		address.setIsEffective(DBConst.TRUE);
		userAddressDao.updateByPrimaryKeySelective(address);
		return SUCCESS;
	}
	
	
	public String setMainAddress( UserAddress address ){
		//将其它设置成普通 
		UserAddress userAddress = new UserAddress();
		userAddress.setIsMain("0");
		UserAddressExample example = new UserAddressExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(address.getUserId());
		userAddressDao.updateByExampleSelective(userAddress, example);
		
		//更新当前的收货地址
		address.setIsMain("1");
		userAddressDao.updateByPrimaryKeySelective(address);
		return SUCCESS;
	}


}